package com.ruoyi.common.core.utils;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * http工具类
 */
public final class HttpUtils {

    /**
     * get
     *
     * @param url
     * @return JsonString
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpGet request = new HttpGet(buildUrl(url, null));
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * get 附带请求参数
     *
     * @param url
     * @param params
     * @return JsonString
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> params) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpGet request = new HttpGet(buildUrl(url, params));
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * get 自定义请求头和附带请求参数
     *
     * @param url
     * @param headers
     * @param params
     * @return JsonString
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpGet request = new HttpGet(buildUrl(url, params));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * post
     *
     * @param url
     * @return JsonString
     * @throws Exception
     */
    public static String doPost(String url) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpPost request = new HttpPost(buildUrl(url, null));
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * Post 附带请求体
     *
     * @param url
     * @param body (JsonString)
     * @return JsonString
     * @throws Exception
     */
    public static String doPost(String url, String body) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpPost request = new HttpPost(buildUrl(url, null));
        request.addHeader("Content-Type", "application/json");
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * post 附带请求体
     *
     * @param url
     * @param bodys
     * @return JsonString
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> bodys) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpPost request = new HttpPost(buildUrl(url, null));
        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * Post 附带请求体
     *
     * @param url
     * @param body
     * @return JsonString
     * @throws Exception
     */
    public static String doPost(String url, byte[] body) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpPost request = new HttpPost(buildUrl(url, null));
        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * Post 自定义请求头和附带请求体
     *
     * @param url
     * @param headers
     * @param body
     * @return JsonString
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> headers, String body) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpPost request = new HttpPost(buildUrl(url, null));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * Put String
     * @param url
     * @param headers 请求头
     * @param params 请求参数
     * @param body 请求体
     * @return JsonString
     * @throws Exception
     */
    public static String doPut(String url, Map<String, String> headers, Map<String, String> params, String body) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpPut request = new HttpPut(buildUrl(url, params));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }

    /**
     * Delete
     *
     * @param url
     * @param headers 请求头
     * @param params 请求参数
     * @return JsonString
     * @throws Exception
     */
    public static String doDelete(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        HttpClient httpClient = wrapClient(url);
        HttpDelete request = new HttpDelete(buildUrl(url, params));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        HttpResponse response = httpClient.execute(request);
        return httpResponse2JsonString(response);
    }


    private static HttpClient wrapClient(String url) {
        if(StringUtils.isBlank(url)) {
            throw new NullPointerException("请求路径为空");
        }
        HttpClient httpClient = new DefaultHttpClient();
        if (url.startsWith("https://")) {
            sslClient(httpClient);
        }
        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 拼接请求参数
     * @param url
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String buildUrl(String url, Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(url);
        if (null != params) {
            StringBuilder sbParam = new StringBuilder();
            for (Map.Entry<String, String> query : params.entrySet()) {
                if (0 < sbParam.length()) {
                    sbParam.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbParam.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbParam.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbParam.append("=");
                        sbParam.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbParam.length()) {
                sbUrl.append("?").append(sbParam);
            }
        }
        return sbUrl.toString();
    }

    /**
     * HttpResponse 转 jsonString
     * @param response
     * @return
     */
    private static String httpResponse2JsonString(HttpResponse response) throws Exception {
        String line = null;
        StringBuilder sb = new StringBuilder();
        BufferedReader b = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8), 8*1024);
        while ((line = b.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

}
